import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { RoleEntity } from './role.entity';
import { Repository, getConnection } from 'typeorm';
import { CommonObjectProps } from '../typings';

@Injectable()
export class RolesService {
  constructor(
    @InjectRepository(RoleEntity)
    private readonly rolesRepository: Repository<RoleEntity>,
  ) {}

  async addRole(role: CommonObjectProps): Promise<RoleEntity> {
    return await this.rolesRepository.save(role);
  }

  async roles(): Promise<RoleEntity[]> {
    return await this.rolesRepository.find();
  }

  // 查单个
  async getRole(id: number): Promise<RoleEntity> {
    return await this.rolesRepository.findOne({ where: { id } });
  }

  // 更新
  async update(id: number, role: CommonObjectProps) {
    const result = await getConnection()
      .createQueryBuilder()
      .update(RoleEntity)
      .set(role)
      .where('id=:id', { id })
      .execute();
    return result;
  }

  // 删除
  async delete(id: number) {
    const result = await getConnection()
      .createQueryBuilder()
      .delete()
      .from(RoleEntity)
      .where('id=:id', { id })
      .execute();
    return result;
  }
}
